package com.guohong.web;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.guohong.common.RestResult;
import com.guohong.constant.ResponseCodeConstant;
import com.guohong.dto.ElTreeDto;
import com.guohong.exception.ServiceException;
import com.guohong.service.MenuService;
import com.guohong.vo.MenuVo;

@RestController
@RequestMapping("/menu")
public class MenuController {
	private final Logger logger = LoggerFactory.getLogger(MenuController.class);

	@Autowired
	private MenuService menuService;

	@RequestMapping(value = "/tree", method = RequestMethod.GET)
	@ResponseBody
	public RestResult<List<ElTreeDto>> getMenuTree() {
		RestResult<List<ElTreeDto>> result = new RestResult<>();

		try {
			ElTreeDto elTreeDto = menuService.getMenuTree();

			result.setCode(ResponseCodeConstant.SUCCESS);
			result.setData(elTreeDto.getChildren());
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setCode(e.getCode());
			result.setMsg(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResponseCodeConstant.FAILED);
			result.setMsg("系统内部错误");
		}

		return result;
	}
	
	@RequestMapping(value = "/tree/only", method = RequestMethod.GET)
	@ResponseBody
	public RestResult<List<ElTreeDto>> getMenuOnlyTree() {
		RestResult<List<ElTreeDto>> result = new RestResult<>();

		try {
			ElTreeDto elTreeDto = menuService.getMenuOnlyTree();

			result.setCode(ResponseCodeConstant.SUCCESS);
			result.setData(elTreeDto.getChildren());
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setCode(e.getCode());
			result.setMsg(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResponseCodeConstant.FAILED);
			result.setMsg("系统内部错误");
		}

		return result;
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public RestResult<Integer> menuAdd(@RequestBody MenuVo menuVo) {
		RestResult<Integer> result = new RestResult<>();

		try {
			Integer count = menuService.insert(menuVo);
			result.setCode(ResponseCodeConstant.SUCCESS);
			result.setData(count);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setCode(e.getCode());
			result.setMsg(e.getMessage());

		} catch (Exception e) {
			e.printStackTrace();

			result.setCode(ResponseCodeConstant.FAILED);
			result.setMsg("系统内部错误");
		}

		return result;
	}
}

